package com.syh.jn.scm.domain.supplier.entity.base;

import cn.redscarf.commons.util.bean.ExtBeanUtils;
import cn.redscarf.commons.spring.SpringContextUtils;
import cn.redscarf.commons.wrapper.Restrictions;
import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.jn.scm.domain.supplier.repository.base.SalesTeamReadRepository;
import com.syh.jn.scm.domain.supplier.repository.base.downstream.DownstreamReadRepository;
import com.syh.jn.scm.domain.support.SuperBusinessAggregate;
import com.syh.jn.scm.dto.supplier.base.salesMan.SalesmanMto;
import com.syh.jn.scm.dto.supplier.base.salesMan.SalesmanSto;
import com.syh.jn.scm.exception.BusinessException;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.UUID;

/**
 * 销售代表管理
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class Salesman extends SuperBusinessAggregate<Long> {
  /**
   * 创建销售代表
   *
   * @param sto
   * @return
   */
  public static Salesman createdSalesmanBySupply(SalesmanSto sto) {
    //初始化创建
    Salesman salesman = Salesman.commonCreatedSalesman(sto);
    ExtBeanUtils.copyProperties(sto, salesman);
    salesman.setUuid(UUID.randomUUID().toString());

    return salesman;
  }

  /**
   * 修改销售代表
   *
   * @param mto
   * @return
   */
  public void modify(SalesmanMto mto) {
    ExtBeanUtils.copyProperties(mto, this);
    this.lastUpdateTimeStamp = System.currentTimeMillis();
  }

  /**
   * 删除销售代表
   */
  public void destroy() {
    SalesTeamReadRepository streadRpository = (SalesTeamReadRepository) SpringContextUtils.getBean(SalesTeamReadRepository.class);
    DownstreamReadRepository dsCustReadRpository = (DownstreamReadRepository) SpringContextUtils.getBean(DownstreamReadRepository.class);
    Wrapper wp = Wrapper.build().append(Restrictions.eq("salesmanId", id));

    int salesmanCount = streadRpository.getCount(wp);
    if (salesmanCount > 0) {
      throw new BusinessException("该销售代表已存在于销售团队，删除失败！");
    }
    salesmanCount = dsCustReadRpository.getCount(wp);
    if (salesmanCount > 0) {
      throw new BusinessException("该销售代表已存在下游客户，删除失败！");
    }
  }

  /**
   * 初始化销售代表
   *
   * @return
   */
  public static Salesman commonCreatedSalesman(SalesmanSto sto) {
    Salesman salesman = new Salesman();
    salesman.status = 1;
    salesman.createTimeStamp = System.currentTimeMillis();
    salesman.lastUpdateTimeStamp = System.currentTimeMillis();
    return salesman;
  }

  /**
   * 在职
   */
  public void enabled() {
    this.status = 1;
  }

  /**
   * 离职
   */
  public void disabled() {
    this.status = -1;
  }

  /**
   * 姓名
   */
  private String name;
  /**
   * 编号
   */
  private String code;
  /**
   * 邮箱
   */
  private String email;
  /**
   * 联系电话
   */
  private String mobile;
  /**
   * 状态: -1离职, 1在职
   */
  private Short status;
  /**
   * 对应团队id
   */
  private Long salesTeamId;
}

